package com.lvyq.myplayer.widget.audio

import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.current.CurrentPlayLstAdapter
import com.lvyq.myplayer.base.BaseActivity
import com.lvyq.myplayer.common.shared.MainAudioSharedPrefsManager
import com.lvyq.myplayer.common.util.DataOperationUtils
import com.lvyq.myplayer.common.util.MockDataUtil
import com.lvyq.myplayer.parcelable.EventPopModeChange
import com.lvyq.myplayer.parcelable.SongInfoData
import com.lvyq.myplayer.service.AudioService
import com.lvyq.myplayer.service.IService
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.runOnUiThread

/**
 * 文件描述：AudioListPopWindow
 * 作者：lvyq
 * 创建时间：2025-03-11
 * 修改时间：2025-03-11
 */
class AudioListPopWindow(
    context:Context,currentPlayAdapter: CurrentPlayLstAdapter?,
    iService: IService?
): PopupWindow() {

    private
    lateinit var headerMode:ImageView
    lateinit var headerTitle:TextView
    var playMode = 0
    var service: IService? = null
    init {
        //设置布局
        val view=LayoutInflater.from(context).inflate(R.layout.pop_play_list,null,false)

        playMode= iService?.getPlayMode() ?:0

        service=iService

        //头部信息
        headerMode  =  view.findViewById<ImageView>(R.id.header_icon)
        headerTitle =  view.findViewById<TextView>(R.id.header_title)
        changeHeaderTitle(playMode,currentPlayAdapter?.itemCount?:0)

        contentView=view
       var  listView =view.findViewById<RecyclerView>(R.id.rvListView)
        listView.layoutManager= LinearLayoutManager(context)

        //适配adapter
        listView.adapter=currentPlayAdapter
        //设置宽度，高度
        width=ViewGroup.LayoutParams.MATCH_PARENT

        //设置高度为屏幕 3/5
        //获取屏幕高度
        val manager= context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point = Point()
        manager.defaultDisplay.getSize(point)
        val windowH = point.y
        height=(windowH*3)/5
        //设置 获取焦点
        isFocusable=true
        //设置外部点击
        isOutsideTouchable=true
        //设置响应外部返回按钮
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        //设置弹出动画
        animationStyle=R.style.pop

        //设置模式点击事件
        headerMode.setOnClickListener {
            //切换播放模式
            changePlayMode(currentPlayAdapter)
        }

        currentPlayAdapter?.setOnItemClickListener(object :CurrentPlayLstAdapter.OnItemClickListener{
            override fun onItemClick(data: SongInfoData, position: Int) {
                BaseActivity.iService?.musicPlayPosition(position,data)
            }

            override fun onItemClickDel(position: Int) {

                //获取当前播放中的position
                var currentAudioPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(context)?.toInt()
                currentAudioPosition?.let {
                    println("播放中的Position"+it+"删除的Position>>"+position)
                    if (it>position){
                        DataOperationUtils.delWithPositionAndReSet(context,position)
                        //删除播放中前面的数据时，-1,这里提前更新
                        MainAudioSharedPrefsManager.saveCurrentAudioPosition(context,(currentAudioPosition-1).toString())
                        iService?.updateCurrentPosition(currentAudioPosition-1)
                    }
                    //删除当前播放中的单曲
                    if (it==position){
                        println("删除正在播放的Position>>"+position)
                        //MainAudioSharedPrefsManager.saveCurrentAudioPosition(context,position.toString())
                        //TODO 强制播放下一曲，忽略播放模式
                        //在删除之前获取当前播放音乐的下一首。再进行删除
                        //PS:删除后songInfoList会频繁更新，这里先取出删除前的数据，同时提前对单曲的position复制
                        var songInfoList = MainAudioSharedPrefsManager.getSongInfoList(context)
                        DataOperationUtils.delWithPositionAndReSet(context,position)
                        if (songInfoList.size>1){
                            //非最后一条。获取删除前的下一首数据
                            if (position==songInfoList.size-1){
                                //删除最后一条。播放第一条
                                var infoData = songInfoList.get(0)
                                infoData.position=0
                                iService?.playForDelCurrent(infoData,0)
                            }else{
                                //非最后一条
                                var infoData = songInfoList.get(position + 1)
                                infoData.position=position
                                iService?.playForDelCurrent(infoData,position)
                            }

                        }else{
                            iService?.playForDelCurrent(MockDataUtil.initSongInfo(),-1)

                        }

                    }
                    if (it<position){
                        //删除之后的数据，不做任何处理
                        DataOperationUtils.delWithPositionAndReSet(context,position)

                    }
                }

                context.runOnUiThread{
                    //后期优化次数条目更新的逻辑，这里暂时写死
                    changeHeaderTitle(playMode,MainAudioSharedPrefsManager.getSongInfoList(context).size)
                    Toast.makeText(context,"删除成功",Toast.LENGTH_SHORT).show()

                }
            }

        })
    }




    /**
     * 切换播放模式
     */
   private fun changePlayMode(adapter: CurrentPlayLstAdapter?) {
        //切换播放模式
        service?.setPlayMode()

        //播放模式切换通知
        var event =EventPopModeChange(true)
        EventBus.getDefault().post(event)

        changeHeaderTitle(service?.getPlayMode()?:0,adapter?.itemCount?:0)
    }

    /**
     * 修改头部文本
     */
    private fun changeHeaderTitle(playMode: Int,count:Int) {
        var title = " "
        when(playMode){
            AudioService.PLAY_MODE_ALL ->{
                headerMode.setImageResource(R.mipmap.pop_play_mode_all)
                title="循环播放(${count}首)"
            }
            AudioService.PLAY_MODE_SINGLE ->{
                headerMode.setImageResource(R.mipmap.pop_play_mode_single)
                title="单曲循环"
            }
            AudioService.PLAY_MODE_RANDOM ->{
                headerMode.setImageResource(R.mipmap.pop_play_mode_random)
                title="随机播放(${count}首)"
            }
        }
        headerTitle.setText(title)
    }

    override fun dismiss() {
        super.dismiss()
        //反注册EventBus
        EventBus.getDefault().unregister(this)
    }
}